﻿using System;
using System.Data;
using System.Data.SqlClient;

namespace UniversityStudentManagemnetSystem.DAO.DAL.Gateway
{
    public class CreditGateway:DAO.Gateway.Gateway
    {
        public double GetAssignedCreditOf(int id)
        {
            Command.CommandText = "SELECT Credit From t_Teacher WHERE Id = @id";
            Command.Parameters.Clear();
            Command.Parameters.Add("@id", SqlDbType.Int).Value = id;
            queryString = GetQueryString(Command);

            double credit = 0;
            try
            {
                Connection.Open();
                DataReader = Command.ExecuteReader();

                if (DataReader.HasRows)
                {
                    while (DataReader.Read())
                    {
                        credit = Convert.ToDouble(DataReader["Credit"]);
                    }
                }
            }
                catch(FormatException exception)
                {
                    throw new Exception(exception.Message);
                }
            catch (Exception exception)
            {
                throw new Exception("Database Error", exception);
            }
            finally
            {
                DataReader.Close();
                DataReader.Dispose();

                if (Connection != null && Connection.State == ConnectionState.Open)
                {
                    Connection.Close();
                }
            }

            return credit;
        }

        public DataTable GetperformingCreditsOf(int teacherId)
        {
            Command.CommandText =
                @"SELECT t_Course.CourseName, t_Course.Credit FROM t_CourseAssignToTeacher INNER JOIN t_Course ON t_CourseAssignToTeacher.CourseId = t_Course.Id WHERE t_CourseAssignToTeacher.TeacherId = @id";
            Command.Parameters.Clear();
            Command.Parameters.Add("@id", SqlDbType.Int).Value = teacherId;
            queryString = GetQueryString(Command);

            DataSet dataSet = new DataSet();
            SqlDataAdapter dataAdapter = new SqlDataAdapter(queryString, Connection.ConnectionString);
            dataAdapter.Fill(dataSet);
            DataTable table = dataSet.Tables[0];
            nbrOfTableRows = table.Rows.Count;
            return table;
        }
    }
}